package com.jyu.edu.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jyu.edu.dto.ResultDto;
import com.jyu.edu.dto.RoleDto;
import com.jyu.edu.dto.UserDto;
import com.jyu.edu.entity.Role;
import com.jyu.edu.entity.User;
import com.jyu.edu.service.RoleService;
import com.jyu.edu.service.UserService;

@RestController
public class RoleController {

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private UserService userService;
	
	@RequiresAuthentication
	@RequestMapping("/getAllRole")
	public List<RoleDto> getAllRole() {
		List<RoleDto> RoleDtos = new ArrayList<RoleDto>();
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User user = userService.getOne(userDto.getId());
		List<Role> roles= null;
		if(user.getRole().getStringRole().equals("superAdmin"))
			roles = roleService.findAll();
		else
			roles = roleService.findAllExceptSA();
		for(Role role : roles) {
			RoleDtos.add(new RoleDto().convert(role));
		}
		return RoleDtos;
	}
	
	
	@RequiresPermissions("role_permission_html")
	@RequestMapping("/addRole")
	public ResultDto addRole(String stringRole,String name) {
		if(roleService.findByStringRole(stringRole)!=null || roleService.findByName(name)!=null) {
			return new ResultDto("角色已存在",null,2);
		}
		Role role = new Role();
		role.setName(name);
		role.setStringRole(stringRole);
		roleService.save(role);
		return new ResultDto("添加成功",null,0);
	}
	
	@RequiresPermissions("role_permission_html")
	@RequestMapping("/upRole")
	public ResultDto upRole(long id,String stringRole,String name) {
		Role role = roleService.getOne(id);
		if(role == null) {
			return new ResultDto("角色不存在!",null,2);
		}
		role.setName(name);
		role.setStringRole(stringRole);
		roleService.save(role);
		return new ResultDto("更新成功",null,0);
	}
	
	@RequiresPermissions("role_permission_html")
	@RequestMapping("/delRole")
	public ResultDto delRole(String ids) {
		String[] idArray = ids.split(",");
		List<Role> roles = new ArrayList<Role>();
		for(String id : idArray) {
			Role role = new Role();
			role.setId(new Long(id));
			roles.add(role);
		}
		roleService.delete(roles);
		return new ResultDto("删除成功",null,0);
	}
	
}
